﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

namespace Agents.Agent
{
    //this page allows an agent to create an order for a client.
    //the page spills all order information from data base for the order form.
    //the agent can enter amounts of each product and the page will calculate the 
    //finall sum based on the clients discount.
    //when the order is finalized it is sent via e-mail to the ordering center.
    //in addition, the page updates agent and client information after the order.
    public partial class CreateOrder : System.Web.UI.Page
    {
        //for holding regular sum
        double sum = 0;
        //for holding sum without tax.
        double taxSum = 0;
        //for holding sum after clients discount.
        double clientSum = 0;
        //for holding the clients discount.
        double discount = 0;

        protected void Page_Load(object sender, EventArgs e)
        {
            //retrieving client and sending it to the screen
            Queries queries = new Queries();
            Clients client = queries.GetClient(Int32.Parse(Request.QueryString["clientId"]));

            nameLbll.Text = client.Name;

            // No stock problems before order
            lblStockProblems.Text = "";
        }

        //function changes string to double
        public double Change(String s)
        {
            String st = s.Substring(0);
            double x = double.Parse(st);
            return x;
        }

        /// <summary>
        /// Calculates the final sum
        /// </summary>
        /// <returns>The list of products that don't have enough stock</returns>
        List<Product> Calculate(out Dictionary<int, int> itemsFromProduct)
        {
            Queries queries = new Queries();
            List<Product> productsNotInStock = new List<Product>();
            itemsFromProduct = new Dictionary<int, int>();

            // Calculate all the products
            foreach (DataGridItem item in dgProducts.Items)
            {
                Product product = queries.GetProduct(Int32.Parse(item.Cells[0].Text));
                int amount = 0;
                Int32.TryParse(((System.Web.UI.WebControls.TextBox)(
                    item.Cells[3].Controls[1])).Text, out amount);

                // Only caculate the rows that have an amount input.
                if (amount > 0)
                {
                    // There is not enough stock of this product
                    if (product.ItemsInStock < amount)
                    {
                        productsNotInStock.Add(product);

                        // Reduce the amount to the number of items in stock
                        ((TextBox)item.Cells[3].Controls[1]).Text = product.ItemsInStock.ToString();
                        amount = product.ItemsInStock;
                    }

                    // Add the total of this row to the total sum.
                    sum = sum + (amount * product.Price);
                    itemsFromProduct.Add(product.Id, amount);
                }
            }

            // Calculate the sum without tax 
            taxSum = sum - ((sum * 16) / 100);

            // Calculate the sum after client's discount.
            clientSum = sum - ((sum * discount) / 100);

            return productsNotInStock;
        }

        //function for finalizing the order
        protected void createOrderBtn_Click(object sender, EventArgs e)
        {
            //creating a query object for accessing the database.
            Queries queries = new Queries();

            // Get the agent who is in the page
            Agents agent = (new Queries()).GetAgentByUserName(Page.User.Identity.Name);

            //retrieving the discount the client has.
            Clients client = queries.GetClient(Int32.Parse(Request.QueryString["clientId"]));
            discount = queries.GetDiscount(client.Id);

            Dictionary<int, int> products = new Dictionary<int, int>();

            //calculate the sum
            if (sum == 0)
            {
                Calculate(out products);
            }

            if (sum > 0)
            {
                // Disable the buttons so the user can't interfere
                cancelOrderBtn.Enabled = false;
                sumBtn.Enabled = false;
                createOrderBtn.Enabled = false;

                queries.MakeOrder(client.Name, sum, agent.Name, commentsTxtbox.Text, products);
                queries.ChangeToActive(agent);
            }

            // Announce success and wait for 2 seconds before redirecting
            lblStockProblems.Text = "ההזמנה בוצעה בהצלחה";
            redirectionTimer.Enabled = true;
        }

        //function redirects the agent back without finalizing the order.
        protected void cancelOrderBtn_Click(object sender, EventArgs e)
        {
            Response.Redirect("WithCustomer.aspx?clientId=" + Request.QueryString["clientId"]);
        }

        //this function calculates the sum and displayes it on the screen without actualy finalizing the order
        protected void sumBtn_Click(object sender, EventArgs e)
        {
            //creating a query object for accessing the database.
            Queries q = new Queries();
            //retrieving the client's discount
            Clients client = q.GetClient(Int32.Parse(Request.QueryString["clientId"]));
            discount = q.GetDiscount(client.Id);
            //making sure the sum wasn't calculated already.

            Dictionary<int, int> products;
            List<Product> productsNotInStock = Calculate(out products);

            //printing all three calculated sums onto screen
            sumMessage.Text = " סך הכל לתשלום לפני הנחה: ";
            sumLable.Text = sum.ToString("F");
            taxSumMessage.Text = "סך הכל לתשלום ללא מעמ: ";
            taxSumLable.Text = taxSum.ToString("F");
            ClientSumMessage.Text = "סך הכל לתשלום לאחר הנחת הלקוח: ";
            ClientSumLable.Text = clientSum.ToString("F");

            // Add message about products not in stock
            if (productsNotInStock.Count > 0)
            {
                lblStockProblems.Text = String.Format(
                    "המוצרים הבאים: {0},\n לא נמצאים במלאי, או שאין מספיק בהם במלאי כרגע." +
                    "\nההזמנה שונתה בהתאם לכמות המוצרים במלאי. באפשרותך לערוך את ההזמנה לפני אישורה.",
                    String.Join(", ", productsNotInStock.Select((p) => p.Name).ToArray()));
            }
        }

        /// <summary>
        /// Redirect back to the admin menu after a few seconds
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void redirectionTimer_Tick(object sender, EventArgs e)
        {
            Response.Redirect("~/Agent/AgentMenu.aspx");
        }
    }
}